<?php
/**
 * Created by PhpStorm.
 * User: fanglong
 * Date: 2017/11/3
 * Time: 09:08
 */

namespace app\queue\model;

use think\Db;
use think\Model;
use think\facade\View;
use think\facade\Cache;
use think\facade\Queue;
use think\queue\Job;
use app\queue\model\Test;
use app\queue\model\LbxBranch;
 
use think\facade\Log;
class order extends model
{
    protected $resultSetType = 'collection';

    /**
     * @var string
     */
    protected $table='vi_lbx_125115330_tbk_orders';

    /**
    *   数据库时间戳自动格式化 如果不需要就设置成false
    */
    // protected $dateFormat = false;
    protected $dateFormat = 'Y-m-d';

    /**
     * @var array
     */
    protected $auto=[];
    // /**
    //  * @var array
    //  */
    // protected $insert=['create_time','update_time'];

    /**
     * @return mixed
     */
    protected function setCreateTimeAttr()
    {
        return $_SERVER['REQUEST_TIME'];

    }

    /**
     * @return mixed
     */
    protected function setUpdateTimeAttr()
    {
        return $_SERVER['REQUEST_TIME'];
    }

    /* 获取淘宝订单接口
    * @param array    $data     传入淘宝参数
    * @return boolean           订单数据
    */
    public function get_order($data){
        include_once __DIR__.'/../../../extend/TaobaoApi/TopSdk.php';

        date_default_timezone_set('Asia/Shanghai');
         
        $result   = array();
        $result['status'] = 0;
 



        $c = new \TopClient;
        $c->appkey    = $data['appkey'];
        $c->secretKey = $data['secretKey'];
        $req = new \TbkOrderDetailsGetRequest;;
        $req->setQueryType("{$data['query_type']}");
        if(!empty($data['position_index']))
        $req->setPositionIndex("{$data['position_index']}");       
        $req->setStartTime("{$data['start_time']}");
        $req->setEndTime("{$data['end_time']}");
        if(!empty($data['page_size']))
        $req->setPageSize("{$data['page_size']}");
        if(!empty($data['page_no']))
        $req->setPageNo("{$data['page_no']}"); 
        if(!empty($data['tk_status']))
        $req->setTkStatus("{$data['tk_status']}");
        if(!empty($data['member_type']))
        $req->setMemberType("{$data['member_type']}");
        $req->setJumpType("{$data['jump_type']}");
        $req->setOrderScene("{$data['order_scene']}");
        $resp = $c->execute($req);
        $jsonStr  = json_encode($resp);
        $results  =  array();
        $results  = json_decode($jsonStr,true);
           
        //code 0 表示接口获取成功 大于0表示错误级别
        //status 1 表示有数据   0 表示无属性
        if(isset($results['data']['results'])){
            
            $result   = $results['data'];
            $result['data'] = array();
            if(!empty($result['results']['publisher_order_dto'])){

                if(count($result['results']['publisher_order_dto']) == count($result['results']['publisher_order_dto'],1)){ 
                    $result['data'][0] = $result['results']['publisher_order_dto']; 
                }else{
                
                    $result['data'] = $result['results']['publisher_order_dto'];    
                }
                unset($result['results']);
                $result['status'] = 1;
                $result['code']   = 0;
                
            }else{
                $result['status']  = 0;
                $result['code']    = 0;
                $result['sub_msg'] = "此时间段无订单数据";
                
            }
            return $result;
        }else{
            if(isset($results['code'])){
                $result['msg'] = $results['msg'];
                $result['sub_msg'] = $results['sub_msg'];
                $result['code']  = $results['code'];
                $result['request_id']   = $results['request_id'];
            }else{
                $result = $results;
                $result['sub_msg'] ='无数据！';
                $result['code']  = 8023;//接口错误
            }
            $result['status']  = 0;
            return $result;
        }
    }

    /* 更新或增加订单接口
    * @param array    $data     传入淘宝参数
    * @return boolean           订单数据
    */
    public function orderUpdate($data,$t_name,$unqid,$queName){



  
        

  
        foreach ($data as $k => $v) {


            try {
               

                switch ($queName) {
                  case 'MinuteOrder':
                    $create_time = date('n',time());
                    $t_name = 'vi_lbx_'.$unqid.'_'.$create_time.'_tbk_orders';
                    break;
                  case 'YueOrder':
                    $create_time = date('n',strtotime($v['tk_create_time']));
                    $t_name = 'vi_lbx_'.$unqid.'_'.$create_time.'_tbk_orders';
                    break;
                  default:
                    # code...
                    break;
                }

                //更新表名
                $this->table = $t_name;
                $cunzai = $this->where(array('trade_parent_id'=>$v['trade_parent_id']))->find();
                if(!empty($cunzai)){
                    $up_info = array(
                        'tk_status'=>$v['tk_status'],
                        'tk_paid_time'=>$v['tk_paid_time'],
                        'create_time'=>$v['tk_create_time'],
                        'tb_paid_time'=>$v['tb_paid_time']
                        );
                    $this->where('trade_parent_id',$v['trade_parent_id'])->save($up_info);
                }else{
                    $ad_info = array(
                        'trade_parent_id'=>$v['trade_parent_id'],'trade_id'=>$v['trade_id'],'total_commission_rate'=>$v['total_commission_rate'],'total_commission_fee'=>$v['total_commission_fee'],'tk_total_rate'=>$v['tk_total_rate'],'tk_status'=>$v['tk_status'],'tk_order_role'=>$v['tk_order_role'],'tk_deposit_time'=>$v['tk_deposit_time'],'create_time'=>$v['tk_create_time'],'tk_commission_rate_for_media_platform'=>$v['tk_commission_rate_for_media_platform'],'tk_commission_pre_fee_for_media_platform'=>$v['tk_commission_pre_fee_for_media_platform'],'tk_commission_fee_for_media_platform'=>$v['tk_commission_fee_for_media_platform'],'terminal_type'=>$v['terminal_type'],'tb_deposit_time'=>$v['tb_deposit_time'],'subsidy_type'=>$v['subsidy_type'],'subsidy_rate'=>$v['subsidy_rate'],'subsidy_fee'=>$v['subsidy_fee'],'site_name'=>$v['site_name'],'site_id'=>$v['site_id'],'seller_shop_title'=>$v['seller_shop_title'],'seller_nick'=>$v['seller_nick'],'refund_tag'=>$v['refund_tag'],'commission_rate'=>$v['pub_share_rate'],'pub_share_pre_fee'=>$v['pub_share_pre_fee'],'commission'=>$v['pub_share_fee'],'order_type'=>$v['order_type'],'item_title'=>$v['item_title'],'price'=>$v['item_price'],'item_num'=>$v['item_num'],'item_link'=>$v['item_link'],'item_img'=>$v['item_img'],'auction_category'=>$v['item_category_name'],'income_rate'=>$v['income_rate'],'tk3rd_type'=>$v['flow_source'],'deposit_price'=>$v['deposit_price'],'click_time'=>$v['click_time'],'alimama_share_fee'=>$v['alimama_share_fee'],'alimama_rate'=>$v['alimama_rate'],'adzone_name'=>$v['adzone_name'],'adzone_id'=>$v['adzone_id'],'num_iid'=>$v['item_id'],'tk3rd_pub_id'=>$v['pub_id']
                        );
                    if($v['tk_status']==3){
                        $ad_info['tk_paid_time'] = $v['tk_paid_time'];
                        $ad_info['earning_time'] = $v['tk_earning_time'];
                        $ad_info['tb_paid_time'] = $v['tb_paid_time'];
                        $ad_info['pay_price']    = $v['pay_price'];
                        $ad_info['alipay_total_price'] = $v['alipay_total_price'];
                    };
                   

                        
                    
                    self::insert($ad_info);
                }
            } catch (Exception $e) {

                write_log('error-订单更新或新增异常-'.$e->getMessage().'-'.$e->getline(),$v,'orderUpdate');
                 
            }
        }
    }



    /**
     * [table_has  判断表不存在创建]
     * @param  string      $table [表名]
     * @return [bool]            [description]
     */
    public function table_has($tables){

        try {
            $cunzai = self::query('SHOW TABLES LIKE "'.$tables.'"');
            if($cunzai){
                return true;
            }else{
                $sql = "
                CREATE TABLE IF NOT EXISTS `$tables` (
                  `id` int(11) NOT NULL,
                  `member_id` bigint(20) DEFAULT NULL,
                  `trade_parent_id` bigint(20) DEFAULT NULL COMMENT '淘宝父订单号',
                  `trade_id` bigint(20) DEFAULT NULL COMMENT '淘宝订单号',
                  `num_iid` bigint(20) DEFAULT NULL COMMENT '商品ID',
                  `item_title` varchar(80) DEFAULT NULL,
                  `item_num` smallint(6) DEFAULT NULL,
                  `price` char(20) DEFAULT NULL,
                  `pay_price` char(20) DEFAULT NULL,
                  `seller_nick` varchar(50) DEFAULT NULL,
                  `seller_shop_title` varchar(50) DEFAULT NULL,
                  `commission` char(20) DEFAULT NULL COMMENT '推广者获得的收入金额',
                  `commission_rate` char(20) DEFAULT NULL COMMENT '推广者获得的分成比率',
                  `create_time` datetime DEFAULT NULL COMMENT '淘客订单创建时间',
                  `earning_time` datetime DEFAULT NULL COMMENT '淘客订单结算时间',
                  `tk_status` smallint(6) DEFAULT NULL COMMENT '淘客订单状态，3：订单结算，12：订单付款， 13：订单失效，14：订单成功',
                  `tk3rd_type` char(20) DEFAULT NULL,
                  `tk3rd_pub_id` int(11) DEFAULT NULL,
                  `order_type` char(20) DEFAULT NULL COMMENT '订单类型，如天猫，淘宝',
                  `income_rate` char(20) DEFAULT NULL COMMENT '收入比率，卖家设置佣金比率+平台补贴比率',
                  `pub_share_pre_fee` char(20) DEFAULT NULL COMMENT '效果预估，付款金额*(佣金比率+补贴比率)*分成比率',
                  `subsidy_rate` char(20) DEFAULT NULL COMMENT '补贴比率',
                  `subsidy_type` char(20) DEFAULT NULL COMMENT '补贴类型，天猫:1，聚划算:2，航旅:3，阿里云:4',
                  `terminal_type` char(20) DEFAULT NULL COMMENT '告位名称',
                  `auction_category` varchar(50) DEFAULT NULL COMMENT '类目名称',
                  `site_id` bigint(20) DEFAULT NULL COMMENT '来源媒体ID',
                  `site_name` varchar(50) DEFAULT NULL COMMENT '来源媒体名称',
                  `adzone_id` bigint(20) DEFAULT NULL COMMENT '广告位ID',
                  `adzone_name` char(20) DEFAULT NULL COMMENT '广告位名称',
                  `alipay_total_price` char(20) DEFAULT NULL COMMENT '付款金额',
                  `total_commission_rate` char(20) DEFAULT NULL COMMENT '佣金比率',
                  `total_commission_fee` char(20) DEFAULT NULL COMMENT '佣金金额',
                  `subsidy_fee` char(20) DEFAULT NULL COMMENT '补贴金额',
                  `relation_id` smallint(6) DEFAULT NULL COMMENT '渠道关系ID',
                  `special_id` smallint(6) DEFAULT NULL COMMENT '会员运营id',
                  `click_time` datetime DEFAULT NULL COMMENT '跟踪时间',
                  `tb_paid_time` varchar(30) DEFAULT NULL,
                  `tk_paid_time` varchar(30) DEFAULT NULL,
                  `tk_order_role` tinyint(2) DEFAULT NULL,
                  `refund_tag` tinyint(2) DEFAULT NULL,
                  `tk_total_rate` char(20) DEFAULT NULL,
                  `alimama_rate` char(20) DEFAULT NULL,
                  `alimama_share_fee` char(20) DEFAULT NULL,
                  `item_img` varchar(300) DEFAULT NULL,
                  `item_link` varchar(300) DEFAULT NULL,
                  `tk_commission_pre_fee_for_media_platform` decimal(10,2) DEFAULT '0.00' COMMENT '预估专项服务费：内容场景专项技术服务费，内容推广者在内容场景进行推广需要支付给阿里妈妈专项\r\n\r\n的技术服务费用。专项服务费＝付款金额＊专项服务费率。',
                  `tk_commission_fee_for_media_platform` decimal(10,2) DEFAULT '0.00' COMMENT '结算专项服务费：内容场景专项技术\r\n\r\n服务费，内容推广者在内容场景进行推广需要支付给阿里妈妈专项的技术服务费用。专项服务费＝结算金额＊专项服务费率。',
                  `deposit_price` varchar(10) DEFAULT NULL,
                  `tb_deposit_time` varchar(30) DEFAULT NULL,
                  `tk_deposit_time` varchar(30) DEFAULT NULL,
                  `tk_commission_rate_for_media_platform` decimal(10,0) DEFAULT '0' COMMENT '专项服务费率：内容场景专项技术服务费率，内容推广者在内容场景进行推广需要按结算金额支\r\n\r\n付一定比例给阿里妈妈作为内容场景专项技术服务费，用于提供与内容平台实现产品技术对接等服务。',
                  `tk_earning_time` varchar(30) NOT NULL COMMENT '订单确认收货后且商家完成佣金支付的时间',
                  `tk_create_time` varchar(30) NOT NULL COMMENT '订单创建的时间，该时间同步淘宝，可能会略晚于买家在淘宝的订单创建时间',
                  `pub_share_rate` varchar(10) NOT NULL COMMENT '从结算佣金中分得的收益比率',
                  `pub_share_fee` varchar(20) NOT NULL COMMENT '结算预估收入=结算金额*提成。以买家确认收货的付款金额为基数，预估您可能获得的收入。因买家退款、您违规推广等原因，可能与您最终收入不一致。最终收入以月结后您实际收到的为准',
                  `pub_id` int(15) NOT NULL COMMENT '推广者的会员id',
                  `item_price` varchar(20) NOT NULL COMMENT '商品单价',
                  `item_id` int(20) NOT NULL COMMENT '商品id',
                  `item_category_name` varchar(40) NOT NULL COMMENT '商品所属的根类目，即一级类目的名称',
                  `flow_source` varchar(30) NOT NULL COMMENT '商品类型',
                  `update_time` varchar(30) NOT NULL COMMENT '修改时间'
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                ";


                  $sql1 = " ALTER TABLE `$tables`
                  ADD PRIMARY KEY (`id`),
                  ADD KEY `create_time` (`create_time`),
                  ADD KEY `tk_status` (`tk_status`),
                  ADD KEY `create_time_2` (`create_time`),
                  ADD KEY `earning_time` (`earning_time`),
                  ADD KEY `adzone_id` (`adzone_id`),
                  ADD KEY `site_id` (`site_id`);";
                  $sql2 = "ALTER TABLE `$tables`
                  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;";
                 self::execute($sql);
                 self::execute($sql1);
                 self::execute($sql2);
                 return true;
     
            }
        } catch (Exception $e) {
            write_log('error-判断表或添加表失败-'.$e->getMessage().'-'.$e->getline(),$v,'table_has');
        }

        
    }


 



 

}   
?>  